import operator
import time
from osv import osv, fields
from osv.orm import intersect
import tools.sql
from tools import config
from tools.translate import _
import netsvc
import datetime


class project_currency(osv.osv):
    _name='project.currency'
    _desciption="Currency System for Contract"
    
    _order = "default_curr desc"

    def _create_currency(self,cr,uid,prj_ctc_id,type='contract',context={}):
        curr_obj=self.pool.get('res.currency')        
        currency_ids=curr_obj.search(cr,uid,[('id','>',0)])
        new_id=False
        for curr in curr_obj.browse(cr,uid,currency_ids):
            curr_default_name=''
            curr_code=curr.code
            try:
                curr_id_def=context['currency_id']
            except:
                curr_id_def=False
            if curr_id_def:
                curr_default_name=curr_obj.read(cr,uid,[curr_id_def],['code'])[0]['code']
            if curr_default_name=='':
                curr_default=curr_code=='VND'
            else:
                curr_default=curr_code==curr_default_name
            current_rate=curr.rate
            try:
                if curr_code in ('VND','USD',curr_default_name):              
                    if type=='contract':
                        new_id=self.create(cr,uid,{'name':curr_code,'rate':current_rate,'contract_id':prj_ctc_id,'project_id':False,'default_curr':curr_default})
                    elif type=='project':
                        new_id=self.create(cr,uid,{'name':curr_code,'rate':current_rate,'project_id':prj_ctc_id,'contract_id':False,'default_curr':curr_default})
            except:
                pass
        return new_id
    
    def name_search(self, cr, uid, name, args=[], operator='ilike', context={}, limit=80):
        args2 = args[:]
        if name:
            args += [('name', operator, name)]
        if 'contract_id' in context:
            ids=[]
            contract_id=context.get('contract_id',False)
            if not contract_id:
                args=[('contract_id','=',0)]
            else:
                #isinstance(contract_id,int):
                args+=[('contract_id','=',contract_id)]                
        elif 'project_id' in context:
            ids=[]
            prj_id=context.get('project_id',False)
            if not prj_id:
                args=[('project_id','=',0)]
            else:
                #isinstance(contract_id,int):
                args+=[('project_id','=',prj_id)]
        #else:
        #        args=[('contract_id','=',0)]
        ids = self.search(cr, uid, args, limit=limit)
        res = self.name_get(cr, uid, ids, context)        
        return res
    
    _columns={
             'name':fields.char('Cur.',size=4,required=True),
             'rate':fields.float('Ex.Rate',digits=(12,2),required=True),
             'contract_id':fields.many2one('kdvn.contract.client','Contract'),
             'project_id':fields.many2one('kdvn.project','Project'),
             'default_curr':fields.boolean('Default'),
             'rounding':fields.float('Rounding',digits=(12,6))
             }
    _defaults = {
        'rate': lambda *a: 0.0        
    }
#    _sql_constraints = [
#        ('name_currency_unique', 'unique (name,contract_id)', 'KDVN Error: The name of the currency must be unique !')
#    ]
    def _onchange_rate_name(self, cr, uid, ids, name):
        return {'value':{'name':name.upper()}}
    
    def compute(self, cr, uid, from_currency_id=False, to_currency_id=False,prj_id=False,amount=1.0,context=None):
        ok=True
        if isinstance(from_currency_id,list):
            from_currency_id=from_currency_id[0]
        
        if isinstance(to_currency_id,list):
            to_currency_id=to_currency_id[0]
                        
        if not isinstance(from_currency_id,int) and not isinstance(to_currency_id,int) and not prj_id:
            return 0.0
        elif not prj_id:
            if isinstance(from_currency_id,int):
                prj_id=self.read(cr,ui,[int(from_currency_id)],['project_id'])[0]['project_id'][0]
            else:
                prj_id=self.read(cr,ui,[int(to_currency_id)],['project_id'])[0]['project_id'][0]
                
        if from_currency_id.__class__.__name__=='str':
            try:
                from_currency_id=self.search(cr,uid,[('project_id','=',prj_id),('name','=',from_currency_id)])[0]
            except:
                from_currency_id=False
                
        if to_currency_id.__class__.__name__=='str':
            try:
                to_currency_id=self.search(cr,uid,[('project_id','=',prj_id),('name','=',to_currency_id)])[0]
            except:
                to_currency_id=False
        if from_currency_id:
            from_rate=self.read(cr,uid,[from_currency_id],['rate'])[0]['rate']
        if to_currency_id:
            to_rate=self.read(cr,uid,[to_currency_id],['rate'])[0]['rate']
            
        if from_currency_id and to_currency_id:
             result=from_rate/to_rate*amount
        elif not prj_id:
            return 0.0
        else:
            prj_curr_id=self.pool.get('account.analytic.account').read(cr,uid,[prj_id],['job_currency'])[0]['job_currency']
            prj_curr_rate=self.read(cr,uid,[prj_curr_id],['rate'])[0]['rate']
            if from_currency_id:
                result=from_rate/prj_curr_rate*amount
            else:
                result=prj_curr_rate/to_rate*amount                            
        return result
    
    def init(self,cr):
#        cr.execute("Select id from project_currency where id=1")
#        if not cr.fetchall():
#            cr.execute("Insert into project_currency(id,name,rate) values (1,'#N/A',0.0)")
#        cr.execute("Select tgname from pg_trigger where tgname='change_default_currency'");
#        res=cr.fetchall()
#        if res:
#            cr.execute("drop TRIGGER change_default_currency on project_currency")
#        cr.execute("CREATE OR REPLACE FUNCTION change_project_currency() RETURNS trigger AS '\
#                    DECLARE\
#                      changed boolean;\
#                    BEGIN\
#                      changed := new.default_curr is TRUE;\
#                      IF changed THEN\
#                         update project_currency set default_curr=False where id in\
#                                                 (Select id from project_currency where contract_id in\
#                                                (select distinct contract_id from project_currency where id=new.id)) and id!=new.id;\
#                        END IF;\
#                      RETURN new;\
#                    END\
#                    ' LANGUAGE plpgsql;")
#        cr.execute("CREATE TRIGGER change_default_currency AFTER INSERT OR UPDATE ON project_currency\
#                            FOR EACH ROW EXECUTE PROCEDURE change_project_currency();")
        
        cr.execute("Create or replace view vwproject_currency as\
                    Select contract_id,max(coalesce(VND,0)) as VND,max(coalesce(USD,0)) as USD,max(coalesce(JPY,0)) as JPY,max(coalesce(EUR,0)) as EUR from\
                                project_currency pc \
                            left join \
                                (Select id,rate as VND from project_currency where name='VND') pcvnd on pc.id=pcvnd.id\
                            left join\
                                (Select id,rate as USD from project_currency where name='USD') pcusd on pc.id=pcusd.id\
                            left join\
                                (Select id,rate as JPY from project_currency where name='JPY') pcjpy on pc.id=pcjpy.id\
                            left join\
                                (Select id,rate as EUR from project_currency where name='EUR') pceur on pc.id=pceur.id\
                    where contract_id>0\
                    group by contract_id")
project_currency()